<?php
namespace App\Services;

class Rsa {

    /**
     * @var 私钥
     */
    var $rsaPrivateKey;

    /**
     * @var 公钥
     */
    var $rsaPublicKey;

    public function __construct()
    {
        $this->rsaPrivateKey = openssl_pkey_get_private(file_get_contents(__DIR__.'/../../config/api-key/rsa_private_key.pem'));
        $this->rsaPublicKey = openssl_pkey_get_public(file_get_contents(__DIR__.'/../../config/api-key/rsa_public_key.pem'));

    }


    /**
     * 加密
     * @param $originalData
     * @return string|void
     */
    /*function encrypt($originalData){

        // if (openssl_private_encrypt($originalData, $encryptData, $this->rsaPrivateKey)) {
        if (openssl_public_encrypt($originalData, $encryptData, $this->rsaPublicKey)) {
            return base64_encode($encryptData);
        } else {
            return false;
        }
    }*/
    function encrypt($originalData){

        $crypto = '';

        foreach (str_split($originalData, 117) as $chunk) {

            openssl_public_encrypt($chunk, $encryptData, $this->rsaPublicKey);

            $crypto .= $encryptData;
        }

        return base64_encode($crypto);
    }


    /**
     * 私钥解密
     * @param $encryptData
     */

    /*function decrypt($encryptData){

        // if (openssl_public_decrypt(base64_decode($encryptData), $decryptData, $this->rsaPublicKey)) {
        if (openssl_private_decrypt(base64_decode($encryptData), $decryptData, $this->rsaPrivateKey)) {

            return $decryptData;

        } else {

            return false;
        }
    }*/
    function decrypt($encryptData){

        $crypto = '';

        foreach (str_split(base64_decode($encryptData), 128) as $chunk) {

            openssl_private_decrypt($chunk, $decryptData, $this->rsaPrivateKey);

            $crypto .= $decryptData;
        }

        return $crypto;
    }

}